# 启动界面主程序
import sys
from PySide6.QtWidgets import QApplication, QMainWindow
from ui_control import Ui_MainWindow
from soft_keyboard import SoftKeyboard
import utils
FOCUSIN  = 10
FOCUSOUT = 11
class ControlWindow(QMainWindow):
	def __init__(self):
		super().__init__()
		self.ui = Ui_MainWindow()
		self.ui.setupUi(self)
		self.hc = utils.HardwareController
		utils.load_config()
		# 启动时检查串口连接情况
		serial_status = utils.check_serial_port()
		self.ui.label.setText(serial_status)
		self.ui.plainTextEdit.installEventFilter(self)
		self.soft_keyboard = SoftKeyboard()

		# 超净台风机（低速）
		self.ui.radioButton_7.clicked.connect(lambda: self.hc.set_fan2(1 if self.ui.radioButton_7.isChecked() else 0))
		# 超净台风机（高速）
		self.ui.radioButton_6.clicked.connect(lambda: self.hc.set_fan2(1 if self.ui.radioButton_6.isChecked() else 0))
		# 紫外灯
		self.ui.radioButton.clicked.connect(lambda: self.hc.set_uv_lamp(1 if self.ui.radioButton.isChecked() else 0))
		# 日光灯
		self.ui.radioButton_2.clicked.connect(lambda: self.hc.set_lighting(1 if self.ui.radioButton_2.isChecked() else 0))
		# 声光报警
		self.ui.radioButton_5.clicked.connect(lambda: self.hc.set_alarm(1 if self.ui.radioButton_5.isChecked() else 0))

		# 反应釜加热器
		self.ui.radioButton_8.clicked.connect(lambda: self.hc.set_reactor_heater(1 if self.ui.radioButton_8.isChecked() else 0))
		# 管道加热器
		self.ui.radioButton_9.clicked.connect(lambda: self.hc.set_duct_heater(1 if self.ui.radioButton_9.isChecked() else 0))
		# 半导体制冷片
		self.ui.radioButton_10.clicked.connect(lambda: self.hc.set_refrigeration(1 if self.ui.radioButton_10.isChecked() else 0))
		# 半导体制冷片风扇
		self.ui.radioButton_13.clicked.connect(lambda: self.hc.set_fan1(255 if self.ui.radioButton_13.isChecked() else 0))

		# 电磁阀
		self.ui.radioButton_11.clicked.connect(lambda: self.hc.set_valve1(1 if self.ui.radioButton_11.isChecked() else 0))
		# 真空泵
		self.ui.radioButton_12.clicked.connect(lambda: self.hc.set_vacuum_pump(1 if self.ui.radioButton_12.isChecked() else 0))

		# 磁力搅拌器转速（QDial控件）
		self.ui.dial.sliderReleased.connect(self.send_motor_speed)
		self.ui.dial.valueChanged.connect(self.update_motor_label)
		# CO2泵转速（QDial控件）
		self.ui.dial_2.sliderReleased.connect(self.send_co2_speed)
		self.ui.dial_2.valueChanged.connect(self.update_co2_label)

		# 控制台发送命令
		self.ui.pushButton.clicked.connect(self.send_console_command)

	def send_console_command(self):
		text = self.ui.plainTextEdit.toPlainText().strip()
		if not text:
			return
		import subprocess
		try:
			result = subprocess.run(text, shell=True, capture_output=True, text=True)
			output = result.stdout + result.stderr
		except Exception as e:
			output = str(e)
		self.ui.textBrowser.append(f"$ {text}\n{output}")
		self.ui.plainTextEdit.clear()
	def eventFilter(self, obj, event):
		if obj in [self.ui.plainTextEdit]:
			print(f"eventFilter: obj={obj}, type={event.type()}")
			if event.type() == FOCUSIN:
				pos = obj.mapToGlobal(obj.rect().bottomLeft())
				self.soft_keyboard.set_target(obj)
				self.soft_keyboard.show_at(pos)
				print("软键盘弹出，控件：", obj, "坐标：", pos)
		return super().eventFilter(obj, event)

	def update_motor_label(self, v):
		self.ui.label_2.setText(f"速度: {v}")

	def update_co2_label(self, v):
		self.ui.label_3.setText(f"速度: {v}")

	def send_motor_speed(self):
		v = self.ui.dial.value()
		self.hc.set_motor_speed(v)

	def send_co2_speed(self):
		v = self.ui.dial_2.value()
		self.hc.set_motor_speed(v)

if __name__ == "__main__":
	app = QApplication(sys.argv)
	window = ControlWindow()
	window.show()
	sys.exit(app.exec())
